package com.cskaoyan.typehandler;

import com.cskaoyan.util.StringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author stone
 * @date 2022/10/12 11:50
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    // 输入映射 #{}
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {
        //使用json工具类将数组转换为字符串
        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,value);
    }

    // getResult 输出映射 查询结果集的封装
    // 从结果集中获得对应的值
    // 将值转换为需要的类型
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);

        return transfer(result);
    }

    @SneakyThrows
    private Integer[] transfer(String result) {
        // 也可以使用json工具类来做转换
        if (!StringUtil.isEmpty(result)) {
            Integer[] integers = objectMapper.readValue(result, Integer[].class);
            return integers;

        }
        return new Integer[0];
    }
}
